package presentation.converters;

import java.util.List;

import javax.el.ELContext;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;

import persistence.CostUnit;
import persistence.LibraryLocation;
import presentation.view_helpers.UserBean;
import business.BusinessObjectAssembler;
import business.SubscriptionLogic;
import business.UserManager;
import business.exception.BusinessException;

public class CostUnitConverter implements Converter {

	private static SubscriptionLogic subscriptionLogic;
	private static UserManager userManager;
	
	static {
		subscriptionLogic = BusinessObjectAssembler.getSubscriptionLogic();
		userManager = BusinessObjectAssembler.getUserManager();	
	}
	
	@Override
	public Object getAsObject(FacesContext fctx, UIComponent comp, String value)
			throws ConverterException {
		CostUnit costUnit = null;
		List<CostUnit> costUnits = null;
		LibraryLocation location = null;
				
		if (value != null && ConverterUtil.isNumber(value)) {
			ELContext ectx = fctx.getELContext();
			UserBean userBean = (UserBean) ectx.getELResolver().getValue(ectx, null, "userBean");
			location = userBean.getLoggedOnUser().getLocation();
			
			try {				
				if (userManager.isAdmin(userBean.getLoggedOnUser())) {
					costUnits = subscriptionLogic.getCostUnits();
				}	
				else {
					costUnits = subscriptionLogic.getCostUnitsForLibraryLocation(location);
				}
				
				for (CostUnit cu : costUnits) {
					if (cu.getId() == Integer.valueOf(value))
						costUnit = cu;
				}
			} catch (BusinessException be) {
				throw new ConverterException(be);
			}
		}
		return costUnit;		
	}

	@Override
	public String getAsString(FacesContext fctx, UIComponent comp, Object value)
			throws ConverterException {
		String retVal = null;
		CostUnit costUnit = (CostUnit) value;
		if (costUnit != null)
			retVal = String.valueOf(costUnit.getId());
		return retVal;
	}

}